const os = require('os');
const fs = require('fs');
const path = require('path')
const http = require('http');


let server;

function openServer() {
    // 防止重复开启
    closeServer();

    // 获取本机的局域网IP和自定义端口
    let SERVER_PORT = 65526;
    let SERVER_IP = getServerIp(); //返回127.0.0.1访问的直接http://localhost:65526

    var server=http.createServer(function (req,res){
        // fs.createReadStream(path.resolve(__dirname,"."+req.url)).pipe(res);
    })

    server.on('request',(req,res)=>{
        res.writeHead(200,{ "Content-Type": "application/json;charset=utf-8", "access-control-allow-origin": "*" });

        // 监听 '/api/authentication'
        if(req.method === "POST" && req.url ==="/api/authentication"){
            let context = {
                code: 200,
                data: { type: 'Hello World!' }
              }
              res.end(JSON.stringify(context));
        }
        else if(req.method ==="GET"){
            fs.createReadStream(path.resolve(__dirname,"."+req.url)).pipe(res);
        }
    });

    // 返回端口开启结果
    return new Promise((resolve,reject)=>{
        server.listen(SERVER_PORT,SERVER_IP,()=>{
            // 服务器正确开启
            resolve(`服务器开启成功，服务器地址: http://${SERVER_IP}:${SERVER_PORT}`)
        });
        server.on("error",(err)=>{
            if(err.code === 'EADDRINUSE'){
                reject(`端口:${SERVER_PORT}被占用,请更换占用端口`)
            }
        });

    });

}

function closeServer(){
    server && server.removeAllListeners();
    server && server.close(()=>{
        console.log("服务接口关闭");
    });
}


// 获取本机的局域网IP
function getServerIp() {
    return "127.0.0.1";  //

    let interfaces = os.networkInterfaces();
    for (let devName in interfaces) {
      let iface = interfaces[devName];
      for (let i = 0; i < iface.length; i++) {
        let alias = iface[i];
        if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
          return alias.address;
        }
      }
    }
  }


  module.exports = {   //注意node的导出方式是module.exports 或exports
    openServer,
    closeServer
  }